package video.simple100;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/***
 * 257. 二叉树的所有路径
 */
public class LeetCode257 {


    @Test
    public void test() {
        TreeNode treeNode1 = new TreeNode(1);
        TreeNode treeNode2 = new TreeNode(2);
        TreeNode treeNode3 = new TreeNode(3);
        TreeNode treeNode4 = new TreeNode(5);
        treeNode1.left = treeNode2;
        treeNode1.right = treeNode3;
        treeNode2.right = treeNode4;
        System.out.println(binaryTreePaths(treeNode1).toString());
    }

    public List<String> binaryTreePaths(TreeNode root) {
        // 1、遍历 (向下传递返回值list 主要用来保存叶子节点返回值)
        // 2、定义上级数据往下传
        // 3、在最底部的叶子节点保存返回值
        List<String> resList = new ArrayList<>();
        StringBuffer sb = new StringBuffer();
        nextNode(root, resList, sb);
        return resList;
    }


    void nextNode(TreeNode root, List<String> resList, StringBuffer sb) {
        if (root == null) {
            return;
        }
        //  ->1  ->2  ->5 每一层的数据都放入sb向下传
        sb.append("->").append(root.val);

        // 判断是否为叶子节点
        if (root.left == null && root.right == null) {
            resList.add(sb.substring(2));
        }

        // 递归遍历
        nextNode(root.left, resList, new StringBuffer(sb));
        nextNode(root.right, resList, new StringBuffer(sb));
    }


    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
